(function() {
    'use strict';

    // 拦截XMLHttpRequest
    const originalOpen = unsafeWindow.XMLHttpRequest.prototype.open;
    const originalSend = unsafeWindow.XMLHttpRequest.prototype.send;

    unsafeWindow.XMLHttpRequest.prototype.open = function(method, url) {
        this._method = method;
        this._url = url;
        return originalOpen.apply(this, arguments);
    };

    unsafeWindow.XMLHttpRequest.prototype.send = function(body) {
        if (this._url.includes('/api/leona/rtb/target/template/add')) {
            const requestData = {
                url: this._url,
                method: this._method,
                data: body,
                timestamp: new Date().toISOString()
            };
            
            // 存储数据
            GM_setValue('xhsApiCaptures', requestData);
            console.log('捕获到API提交数据:', requestData);

            sendToServer(body)
        }
        return originalSend.apply(this, arguments);
    };

    // 拦截fetch请求
    const originalFetch = unsafeWindow.fetch;
    unsafeWindow.fetch = function(input, init) {
        const url = typeof input === 'string' ? input : input.url;
        if (url.includes('/api/leona/rtb/target/template/add')) {
            const requestData = {
                url: url,
                method: init?.method || 'GET',
                data: init?.body,
                timestamp: new Date().toISOString()
            };
            
            // 存储数据
            const savedData = GM_getValue('xhsApiCaptures', []);
            savedData.push(requestData);
            GM_setValue('xhsApiCaptures', savedData);
            
            console.log('捕获到API提交数据(Fetch):', requestData);
        }
        return originalFetch.apply(this, arguments);
    };



    function sendToServer(data) {
        GM_xmlhttpRequest({
            method: 'POST',
            url: 'http://localhost:5000/api/monitor_target_config',
            data: JSON.stringify({ target_config_data: data }),
            headers: {
                'Content-Type': 'application/json'
            },
            onload: function(response) {
                console.log('数据已发送到服务器', response);
            },
            onerror: function(error) {
                console.error('发送数据到服务器失败', error);
            }
        });
    }

    // 添加简单调试按钮
    const debugBtn = document.createElement('button');
    debugBtn.textContent = '查看捕获数据';
    debugBtn.style.position = 'fixed';
    debugBtn.style.bottom = '10px';
    debugBtn.style.right = '10px';
    debugBtn.style.zIndex = '9999';
    debugBtn.onclick = () => {
        const data = GM_getValue('xhsApiCaptures', {});
        alert('最终捕获的数据:', data);
    };
    document.body.appendChild(debugBtn);
})();